<script lang="ts" setup>
import {ref} from "vue";
import axios from "axios";
import router from "@/router";
import {addNewPerfumeInCart} from '@/util/checkHasStore'

import 'vue-toast-notification/dist/theme-sugar.css';
import {useToast} from 'vue-toast-notification';

const $toast = useToast();//消息提示栏

const userInfo = ref(Object)
const token = localStorage.getItem("wiki-auth-token")

//获取用户信息
const getUserInfo = () => {
  axios.post("/api/auth/userinfo", {}, {
    headers: {
      token: token
    }
  }).then(res => {
    // console.log(res)
    if (res.data.success) {
      userInfo.value = res.data.message
    } else {
      window.location.href = "/"
    }
  })
}
const initData = () => {
  getUserInfo()
  getMyOrderInfo()
  getMyCollectPerfumes()
}
const columns = [
  {
    name: 'orderId',
    required: true,
    label: '订单编号',
    align: 'left',
    field: row => row.orderId,
    format: val => `${val}`,
    sortable: true
  },
  {name: 'inputTime', align: 'center', label: '下单时间', field: 'inputTime', sortable: true},
  {name: 'address', label: '送货地址', field: 'address', sortable: true},
  {
    name: 'orderPerfumeRefVos', label: '购买物品', field: 'orderPerfumeRefVos', align: 'left',
    format: val => {
      if (Array.isArray(val)) {
        return val.map(el => `名：${el.perfumeVo.name}, 数量: ${el.count}`).join('; ');
      } else {
        // console.log(val)
        return '';  // 如果val不是数组，返回一个空字符串
      }
    }, wrap: true
  }
]

const collectPerfumes = ref([])
const myOrderInfo = ref([])
//获取我收藏的香水列表
const getMyCollectPerfumes = () => {
  axios.post(`/api/userData/myCollectPerfume/${collectPage.value.page}/${collectPage.value.size}`, {}, {
    headers: {
      token: token
    }
  }).then(res => {
    console.log(res)
    const msg = res.data.message
    collectPage.value.total = msg.total
    collectPerfumes.value = msg.list
  })
}
const checkPage = () => {
  console.log(collectPage.value)
  getMyCollectPerfumes()
}
const getMyOrderInfo = () => {
  axios.post("/api/order/getAllByMy", {}, {
    headers: {
      token: token
    }
  }).then(res => {
    console.log(res)
    if (res.data.success) {
      myOrderInfo.value = res.data.message
    } else {
      window.location.href = "/"
    }
  })
}
const collectPage = ref({
  page: ref(1),
  size: ref(10),
  total: ref(0)
})
const unCollectIt = (id) => {
  axios.post(`/api/userData/unCollect/${id}`, {}, {
    headers: {
      token: token
    }
  }).then(res => {
    console.log(res)
    if (res.data.success) {
      getMyCollectPerfumes()//重新初始化收藏列表
    } else {
      alert("取消收藏失败")
    }
  })
}
const joinCart = (item) => {
  console.log(item)
  addNewPerfumeInCart({name: item.name, count: 1, price: item.price, id: item.perfumeId, img: item.img})
}
const goDetail = (index) => {
  router.push("/perfume/detail?id=" + index)
}
const loginOut = () => {
  localStorage.removeItem("wiki-auth-token")
  $toast.open({
    type:"success",
    message:"退出登录",
    position:"bottom-right"
  })
  window.location.href = "/"
}
initData()
</script>

<template>
  <div class="my-main-box">
    <div class="q-pa-md row items-start q-gutter-md w100p">
      <q-card bordered flat style="width: 100%;">
        <div class="d-flex">
          <q-img
              :src="userInfo.headimgurl"
              style="width: 400px;max-height: 60vh;min-height: 300px;margin: 20px;"
          />
          <q-card-section>
            <div class="text-overline text-orange-9">用户信息</div>
            <div class="text-h5 q-mt-sm q-mb-xs">{{
                userInfo.name
              }}({{ userInfo.sex == 1 ? "男士" : userInfo.sex == 2 ? "女士" : "其他" }})
            </div>
            <div class="text-h6 q-mt-sm q-mb-xs">{{ userInfo.mail }}</div>
            <div class="text-caption text-grey">
              创建时间{{ userInfo.inputTime }}
            </div>
            <q-btn color="primary" style="width: 200px" @click="loginOut">
              <div class="ellipsis">
                退出登录
              </div>
            </q-btn>
          </q-card-section>

        </div>
        <div style="flex: 1;display: flex;flex-direction: column;margin-right: 20px;margin-left: 20px;">
          <div style="margin-top: 20px;">
            <div class="text-h6">收藏香水列表</div>
            <q-list bordered separator style="min-height: 400px; position: relative;">
              <q-item v-for="item in collectPerfumes" :key="item.perfumeId" v-ripple clickable
                      style="display: flex;justify-content: space-between">
                <q-tooltip>
                  点击图片或者标题可以跳转详情页
                </q-tooltip>
                <q-item v-ripple clickable @click="goDetail(item.perfumeId)">
                  <img :src="item.img" alt="" height="100px" style="margin-right: 30px;">
                  <q-item-section>
                    <q-item-label> {{ item.name }}</q-item-label>
                    <q-item-label caption>{{ item.smell }}</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item-section avatar style="display: flex">
                  <q-avatar color="red-7" icon="delete" rounded text-color="white"
                            @click="unCollectIt(item.perfumeId)">
                    <q-tooltip>移除收藏夹</q-tooltip>
                  </q-avatar>
                  <view style="height: 15px"></view>
                  <q-avatar color="amber-9" icon="shopping_cart" rounded text-color="white"
                            @click="joinCart(item)">
                    <q-tooltip>加入购物车</q-tooltip>
                  </q-avatar>

                </q-item-section>
              </q-item>
              <q-item style="display: flex;align-items: center;justify-content: center;position: absolute;bottom: 0; left: 50%;  /* 水平偏移50% */
  transform: translateX(-50%);  /* 将元素向左移动它自身宽度的一半，实现水平居中 */">
                <q-pagination
                    v-model="collectPage.page"
                    :max="collectPage.total > collectPage.size 
                    ? collectPage.total / collectPage.size != 0
                    ?(collectPage.total / collectPage.size) + 1:collectPage.total / collectPage.size : 1"
                    direction-links
                    @click="checkPage"
                />
              </q-item>
            </q-list>
          </div>
          <div style="height: 80px;"></div>
          <div>
            <q-table
                :columns="columns"
                :rows="myOrderInfo"
                class="my-sticky-column-table"
                row-key="orderId"
                title="订单信息"
            />
          </div>
          <div style="height: 80px;"></div>
        </div>
      </q-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.my-main-box {
  width: 100vw;
}

.my-sticky-column-table {
  max-width: 90vw;
  table-layout: fixed; /* 强制表格使用固定布局 */
}

thead tr:first-child th:first-child {
  background-color: #fff;
}

td {
  width: 200px;
  word-wrap: break-word;
  max-width: 200px;
}

td:first-child {
  background-color: #f5f5dc;
}

th:first-child,
td:first-child {
  position: sticky;
  left: 0;
  z-index: 1;
}


</style>